%%% -------------------------------------------------------------------
%%% Author  : Bearice
%%% Description :
%%%
%%% Created : 2010-5-7
%%% -------------------------------------------------------------------
-module(minitrue_rpc_registry).

-behaviour(gen_server).
%% --------------------------------------------------------------------
%% Include files
%% --------------------------------------------------------------------
-include("rpc.hrl").
-include_lib("stdlib/include/qlc.hrl").
%% --------------------------------------------------------------------
%% External exports
-export([start_link/1,register_service/1,find_service/1]).

%% gen_server callbacks
-export([init/1, handle_call/3]).

%% ====================================================================
%% External functions
%% ====================================================================
start_link(Table)->
	gen_server:start_link({local,?MODULE}, ?MODULE, Table, []).

register_service(Service) when is_record(Service, service) ->
	gen_server:call(?MODULE, {register,Service}).

find_service(Name) when is_list(Name) ->
	gen_server:call(?MODULE, {find,Name}).
%% ====================================================================
%% Server functions
%% ====================================================================

%% --------------------------------------------------------------------
%% Function: init/1
%% Description: Initiates the server
%% Returns: {ok, State}          |
%%          {ok, State, Timeout} |
%%          ignore               |
%%          {stop, Reason}
%% --------------------------------------------------------------------
init(Table) ->
    {ok, Table}.

%% --------------------------------------------------------------------
%% Function: handle_call/3
%% Description: Handling call messages
%% Returns: {reply, Reply, State}          |
%%          {reply, Reply, State, Timeout} |
%%          {noreply, State}               |
%%          {noreply, State, Timeout}      |
%%          {stop, Reason, Reply, State}   | (terminate/2 is called)
%%          {stop, Reason, State}            (terminate/2 is called)
%% --------------------------------------------------------------------
handle_call({register,Service},_,Table)->
	R = ets:insert(Table, Service),
	{reply,R,Table};

handle_call({find,Name},_,Table)->
	R = ets:lookup(Table, Name),
	{reply,R,Table};

handle_call(_, _, State) ->
    {reply, {error,unknow_request}, State}.
